package nl.xs4all.dylanschell.deckprinter.parser;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import nl.xs4all.dylanschell.deckprinter.model.DeckDescriptor;
import nl.xs4all.dylanschell.deckprinter.services.DeckParser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Set;

@Singleton
public class GenericDeckParser implements DeckParser
{
    private Set<DeckParser> parsers;

    @Inject
    public GenericDeckParser(Set<DeckParser> parsers)
    {
        this.parsers = parsers;
    }

    public DeckDescriptor parseDeck(URL url, String name)
    {
        try
        {
            return parseDeck(url.openStream(), name);
        } catch (IOException e)
        {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return null;
    }

    public DeckDescriptor parseDeck(InputStream is, String name)
    {
        try
        {
            byte[] bytes = readStream(is);
            for (DeckParser parser : parsers)
            {
                try
                {
                    DeckDescriptor desc = parser.parseDeck(new ByteArrayInputStream(bytes), name);
                    if (desc != null)
                    {
                        return desc;
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] readStream(InputStream is)
            throws IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int nRead = 0;
        while (nRead >= 0)
        {
            bos.write(buffer, 0, nRead);
            nRead = is.read(buffer);
        }
        return bos.toByteArray();
    }
}
